import requests
from concurrent.futures import ThreadPoolExecutor, as_completed


class CameraConnector:
    def __init__(self, device_serial):
        self.device_serial = device_serial
        self.base_url = "http://iot.bova.tech:5913"
        self.redirected_url = None
        self.cookies = {}

    def connect(self):
        # 发起初始连接请求
        response = requests.get(f"{self.base_url}/web/{self.device_serial}/http/127.0.0.1%3A80%2F")
        
        if response.status_code == 200:
            # 检查是否有重定向
            if response.history:
                # 获取重定向后的 URL
                self.redirected_url = response.url
                self.cookies = response.cookies.get_dict()
                print(f"Device {self.device_serial} connected successfully, redirected to: {self.redirected_url}")
            else:
                print(f"Device {self.device_serial} connection failed, no redirect.")
        else:
            print(f"Device {self.device_serial} failed to connect:", response.text)

    def get_camera_info(self):
        if not self.redirected_url:
            print(f"Device {self.device_serial} not connected.")
            return None
        
        # 使用重定向后的 URL 请求摄像头信息
        camera_info_url = f"{self.redirected_url}/api/system/info"
        response = requests.get(camera_info_url, cookies=self.cookies)
        
        if response.status_code == 200:
            return response.json()  # 返回摄像头信息
        else:
            print(f"Failed to get camera info for device {self.device_serial}:", response.text)
            return None

def fetch_camera_data(serial):
    connector = CameraConnector(serial)
    connector.connect()
    return serial, connector.get_camera_info()

def main():
    device_serials = [
        "d4eb5a007b8411f2d175",
        "d4eb5a007b8411f2d176",
        "d4eb5a007b8411f2d177",
        # 添加更多序列号...
    ]

    camera_data = {}

    with ThreadPoolExecutor(max_workers=10) as executor:  # 设置并发数为10，可以根据需求调整
        future_to_device = {executor.submit(fetch_camera_data, serial): serial for serial in device_serials}

        for future in as_completed(future_to_device):
            serial, data = future.result()
            if data is not None:
                camera_data[serial] = data
    
    for serial, data in camera_data.items():
        print(f"Data from device {serial}: {data}")

if __name__ == "__main__":
    main()